<?php
include_once("../module/product/includes/plugin_order_class.php");
include("../lang/cn/company_type_config.php");
$order = new order;

$editid = 0;
if($_GET['editid'] && $_GET['editid']>0){
    $editid = $_GET['editid'];
}

if($_POST['act'] && $_POST['act']=='op'){
    if($_POST['submit']==$lang['del']){//删除商品
        if(!empty($_POST['chk']) && $editid>0)
        {
            $sql = "select product_ids from ".FREESHIPEXPRESS." where id={$editid}";
            $db->query($sql);
            $productIdsOld = $db->fetchField('product_ids');
            if(!empty($productIdsOld)){
                $productIdsNew = ','.$productIdsOld.',';
                foreach ($_POST['chk'] as $v)
                {
                    $productIdsNew = str_replace(','.$v.',', ',', $productIdsNew);
                }
                
                $productIdsNew = trim($productIdsNew,',');
                $proNum = 0;
                if(strpos($productIdsNew, ',')!==false){
                    $productidsTemp = explode(',', $productIdsNew);
                    $proNum = count($productidsTemp);
                }
                $sql = "update ".FREESHIPEXPRESS." set product_ids='{$productIdsNew}',product_num={$proNum} where id={$editid}";
                $db->query($sql);
            }
        }
    }
    if($_POST['submit']=='提交' && $_POST['displayorder']){
        if($editid>0){
            $displayorder = array();
            foreach($_POST['displayorder'] as $key=>$val)
            {
                $displayorder[] = array('product_id'=>$key,'displayorder'=>$val);
            }
            $displayorder = arraySortByField($displayorder, 'displayorder','asc');
            $productIds = "";
            foreach($displayorder as $div)
            {
                $productIds .= empty($productIds)?$div['product_id']:','.$div['product_id'];
            }
            $sql = "update ".FREESHIPEXPRESS." set product_ids='{$productIds}' where id={$editid}";
            $db->query($sql);
        }
    }
    msg('?m=activity&s=free_shipping_product.php&editid='.$editid);
}

if($_POST['act'] && $_POST['act']=='add'){//保存添加商品
    $id=$_POST['id']*1;
    if(!empty($_POST['chk']) && $id>0)
    {
        $sql = "select product_ids from ".FREESHIPEXPRESS." where id={$id}";
        $db->query($sql);
        $productIdsOld = $db->fetchField('product_ids');
        $productids = explode(',', $productIdsOld);
        $idsArr = array_unique(array_merge($productids,$_POST['chk']));
        $productIdStr = '';
        $proNum = 0;
        foreach($idsArr as $val)
        {
            if(!empty($val)){
                $productIdStr .= empty($productIdStr)?$val:','.$val;
                $proNum++;
            }
        }
        
        $productIdStr = trim($productIdStr);

        $sql = "update ".FREESHIPEXPRESS." set product_ids='{$productIdStr}',product_num={$proNum} where id={$id}";
        $db->query($sql);
    }
    echo "<script>window.parent.main.location.reload();</script>";
    echo "<script>window.parent.DialogManager.close('activity');</script>";
    die;
}
if($_GET['type'] && $_GET['type']=='addPro'){//添加商品的弹出层
    $id=$_GET['id']?$_GET['id']:NULL;
    $product_id=$_GET['product_id']?$_GET['product_id']:NULL;
    $key=$_GET['key']?$_GET['key']:NULL;
    $catid=$_GET['catid']?$_GET['catid']:NULL;
    $code=$_GET['code']?$_GET['code']:NULL;
    $tags=$_GET['tags']?$_GET['tags']:NULL;
    
                            if(!empty($key))
                                $scl.=" and ( pname like '%$key%' )";
                            if(!empty($catid))
                                $scl.=" and LOCATE($catid,catid)=1";
                            if(!empty($tags))
                                $scl.=" and (tags like '$tags%' or tags like '%,$tags%') ";
                            if(!empty($code))
                                $scl.=" and code = '$code'";
                            if(!empty($product_id)){
                                $scl.=" and id in($product_id)";
                                $_GET['page_size'] = substr_count($product_id,',')+1;
                            }
    
                            if($_GET['brand'] && $_GET['brandid']){
                                $scl.=" and brandid = '$_GET[brandid]'";
                            }else{
                                $scl.=" and brand like '".addslashes($_GET[brand])."%'";
                            }
    
                            if ($_GET['page_size']){
                                $page_size=$_GET['page_size'];
                            }else{
                                $_GET['page_size']=$page_size=20;
                            }
                            
                            $sql="SELECT id,catid,tags,brand,pic,pname,price,show_price,market_price,code,tax_rate FROM ".PRO." where status>0 $scl order by id desc";
                            //====================
                            include_once("../includes/page_utf_class.php");
                            $page = new Page;
                            $page->listRows=$page_size;
                            if (!$page->__get('totalRows')){
                                $db->query($sql);
                                $totalRows = $page->totalRows = $db->num_rows();
                            }else{
                                $totalRows = $_GET['totalRows'];
                            }
                            $sql .= "  limit ".$page->firstRow.",".$page->listRows;
                            $de['page'] = $page->prompt();
                            //=====================
                            $db->query($sql);
                            $de['list']=$db->getRows();
                            //$tpl->assign("de",$de);
    
                            if(!empty($catid) and $de['list'])
                            {
                                $max=$catid.'99';
                                $min=$catid.'00';
                                $ss=" and catid<=$max and catid>=$min ";
                            }
                            elseif(!empty($catid) and !$de['list'])
                            {
                                $catid=substr($catid,0,-2);
                                $max=$catid.'99';
                                $min=$catid.'00';
                                $ss=" and catid<=$max and catid>=$min ";
                            }
                            else
                                $ss=" and catid<9999 ";
    
                                $sql="SELECT cat,catid FROM ".PCAT." where 1 $ss order by catid";
                                $db->query($sql);
                                $re=$db->getRows();
                                if(!$re)
                                {
                                    $catid=substr($catid,0,-2);
                                    $max=$catid.'99';
                                    $min=$catid.'00';
                                    $ss=" and catid<=$max and catid>=$min ";
                                    $sql="SELECT cat,catid FROM ".PCAT." where 1 $ss order by catid";
                                    $db->query($sql);
                                    $re=$db->getRows();
                                }
                                $tpl->assign("re",$re);
    
                                include_once("$config[webroot]/module/product/includes/plugin_pro_class.php");
                                //================================================================
                                $pro=new pro();
                                $de['all_tags']=$pro->get_tags();
    
                                if ($_GET['tags']){
    
                                    $de['tags']=array($_GET['tags']);
    
    
                                }
    
                                //所属分类，产品标签
                                $catids = "";
                                $tagids = "";
                                $catTmp = array();
                                $tagTmp = array();
                                foreach ($de['list'] as $dk=>$dv)
                                {
                                    $catids .= $dv['catid'].",";
                                    $tagids .= $dv['tags'].",";
                                }
                                $catids = rtrim($catids,",");
                                if($catids!=""){
                                    $sql="SELECT cat,catid FROM ".PCAT." WHERE catid IN (".$catids.")";
                                    $db->query($sql);
                                    $catTmp=$db->getRows();
                                }
                                $catArr = array();
                                foreach ($catTmp as $cav){
                                    $catArr[$cav['catid']] = $cav['cat'];
                                }
                                $tagids = rtrim($tagids,",");
                                if($tagids!=""){
                                    $sql="SELECT id,tags FROM ".TAG." WHERE id IN (".$tagids.")";
                                    $db->query($sql);
                                    $tagTmp=$db->getRows();
                                }
                                $tagArr = array();
                                foreach ($tagTmp as $tav)
                                {
                                    $tagArr[$tav['id']] = $tav['tags'];
                                }
    
    
                                foreach ($de['list'] as $dk=>$dv)
                                {
                                    $de['list'][$dk]['catname'] = $catArr[$dv['catid']];
                                    $tagsTmp = explode(",", $dv['tags']);
                                    $tagStr = "";
                                    foreach ($tagsTmp as $ttv)
                                    {
                                        $tagStr .= $tagArr[$ttv].",";
                                    }
                                    $de['list'][$dk]['tagnames'] = rtrim($tagStr,",");
                                }
    
                                $tpl->assign("de",$de);
                                $tpl->assign("countpro",$totalRows);
                                $condTemp = $_GET;
                                unset($condTemp['m']);
                                unset($condTemp['s']);
                                $cond = "";
                                if(count($condTemp)){
                                    $cond = "&".http_build_query($condTemp);
                                }
                                $tpl->assign("cond",$cond);
                                $tpl->assign("config",$config);
                                $tpl->display("activity_product.htm");
                                exit;
}

//产品列表
$sql = "select product_ids from ".FREESHIPEXPRESS." where id={$editid}";
$db->query($sql);
$productIds = $db->fetchField('product_ids');
$de['list'] = array();
$de['page'] = array();
if(!empty($productIds)){
    //----------------------分仓
    $general_shop =$order->get_general_shop();
    
    if ($general_shop!=0&&$general_shop!=$_GET['stock_shop']&&isset($_GET['stock_shop'])){
        msg('noright.php');
        exit;
    }
    if ($general_shop){
        $_GET['stock_shop'] =$general_shop;
    }
    if ($_GET['stock_shop']){
        $str =" and stock_shop = '$_GET[stock_shop]' ";
    }
    if($_GET['product_id']){
        $_GET['product_id'] = trim(trim($_GET['product_id'],','));
        $proA = explode(',',$productIds);
        $proB = explode(',',$_GET['product_id']);
        $pro = array_intersect($proA,$proB);
        if(!empty($pro)){
            $productIds = implode(',', $pro);
        }else{
            $productIds = "";
        }
        
        $_GET['page_size'] = substr_count($productIds,',')+1;
        $_GET['totalRows'] = $_GET['page_size'];
    }
    if ($_GET['page_size']){
        $page_size=$_GET['page_size'];
    }else{
        $_GET['page_size']=$page_size=20;
    }
    
    if(!empty($productIds)){
        $productIds = trim($productIds,',');
        $sql = "select * from ".PRO." where id in({$productIds}) {$str} order by find_in_set(id,'{$productIds}') ";
        include_once("../includes/page_utf_class.php");
        $page = new Page;
        $page->listRows=$page_size;
        if (!$page->__get('totalRows')){
            $db->query($sql);
            $totalRows = $page->totalRows = $db->num_rows();
        }else{
            $totalRows = $_GET['totalRows'];
        }
        $sql .= "  limit ".$page->firstRow.",".$page->listRows;
        $de['page'] = $page->prompt();
        
        $db->query($sql);
        $de['list']=$db->getRows();
    }
    
    $stock_shops=$order->get_stock_shops();
    $tpl->assign("stock_shops",$stock_shops);
}

foreach($de['list'] as $key=>$val)
{

    //获取产品类别
    $tmp=array();
    if ($val['catid']){
        $sql = "select cat from ".PCAT." where '$val[catid]' like concat(`catid`,'%')  order by catid asc";
        $db->query($sql);
        foreach ($cat=$db->getRows() as $item){
            $tmp[]=$item['cat'];
        }
    }

    $tmp2=explode(',', $val['pic']);
    $de['list'][$key]['pic']=$tmp2[0];
     
    $de['list'][$key]['cat']=implode('->', $tmp);

}

//产品标签
$tagids = "";
$tagTmp = array();
foreach ($de['list'] as $dk=>$dv)
{
    if($dv['tags']){
        $tagids .= $dv['tags'].",";
    }
}
$tagids = rtrim($tagids,",");
if($tagids!=""){
    $sql="SELECT id,tags FROM ".TAG." WHERE id IN (".$tagids.")";
    $db->query($sql);
    $tagTmp=$db->getRows();
}

$tagArr = array();
foreach ($tagTmp as $tav)
{
    $tagArr[$tav['id']] = $tav['tags'];
}


foreach ($de['list'] as $dk=>$dv)
{
    $tagsTmp = explode(",", $dv['tags']);
    $tagStr = "";
    foreach ($tagsTmp as $ttv)
    {
        $tagStr .= $tagArr[$ttv].",";
    }
    $de['list'][$dk]['tagnames'] = rtrim($tagStr,",");
}

$condTemp = $_GET;
unset($condTemp['m']);
unset($condTemp['s']);
$cond = "";
if(count($condTemp)){
    $cond = "&".http_build_query($condTemp);
}
$tpl->assign("cond",$cond);

$tpl->assign('productIds',$productIds);
$tpl->assign('de',$de);
$tpl->assign("countpro",$totalRows);
$tpl->display('free_shipping_product_list.htm');
?>